package ar.uba.fi.tonyvaliente.commands;

import java.util.LinkedList;

import ar.uba.fi.tonyvaliente.documents.DocumentManager;
import ar.uba.fi.tonyvaliente.documents.QueryDocumentsResult;

public class QueryDocumentsCommand extends Command {

	private boolean recognized;
	private String query;
	private boolean showDetails;
	private LinkedList<Integer> documents;

	public QueryDocumentsCommand(String[] args) {
		super(args);

		recognized = false;
		query = null;
		showDetails = false;
		documents = new LinkedList<Integer>();

		if (args.length > 0) {
			String command = args[0];
			command = command.toLowerCase();
			if (command.equals("-query")) {
				recognized = true;
				if (args.length > 1) {
					query = args[1];
				}
				if (args.length > 2) {
					showDetails = args[2].equals("showDetails");
				}
			}
		}
	}

	private CommandResult queryDocuments() {
		QueryDocumentsResult queryDocumentsResult = DocumentManager
				.queryDocuments(query, showDetails);
		if (queryDocumentsResult.getResults().size() == 0)
			return new CommandResult(true, true, "0 documents found");
		else {
			StringBuffer documentList = new StringBuffer();
			documentList.append(queryDocumentsResult.getMessages());
			documents = queryDocumentsResult.getResults();
			documentList.append("\n ");
			documentList.append(documents.size());
			documentList.append(" documents found");
			return new CommandResult(true, true, documentList.toString());
		}
	}

	public LinkedList<Integer> getDocumentIds()
	{
		return documents;
	}
	
	public CommandResult execute() {
		if (!recognized)
			return CommandResult.NOT_RECOGNIZED;

		if (query == null)
			return new CommandResult(true, false, "Missing query expression");

		if (!isValidQuery(query))
			return new CommandResult(true, false, "Invalid query expression");

		return queryDocuments();
	}

	public String getSignature() {
		return "-query \"boolean query\" [showDetails]";
	}

	public String getDescription() {
		return "Query the index and return a document's list that matches the query";
	}

	public String[] getExamples() {
		return new String[] {
				String.format("-query \"%s\"", "home OR car"),
				String.format("-query \"%s\" showDetails", "home OR car") 
				};
	}

	private static boolean isValidQuery(String query) {
		// TODO: implementar
		return true;
	}
}
